package com.zb.influx;

import org.influxdb.InfluxDB;
import org.influxdb.dto.Point;
import org.influxdb.dto.Query;
import org.influxdb.dto.QueryResult;
import org.influxdb.impl.InfluxDBResultMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class InfluxRepository {

    @Autowired
    private InfluxDB influxDB;
    @Value("${spring.influx.db}")
    private String dbName;

    public void add(Object obj) {
        Point.Builder pointBuilder = Point.measurementByPOJO(obj.getClass());
        Point point = pointBuilder.addFieldsFromPOJO(obj)
                .time(LocalDateTime.now().plusHours(8).toInstant(ZoneOffset.of("+8"))
                        .toEpochMilli(), TimeUnit.MILLISECONDS).build();
        influxDB.setDatabase(dbName);
        influxDB.write(point);
        influxDB.close();
    }

    public <T> List<T> query(String ql, Class<T> clazz) {
        QueryResult query = influxDB.query(new Query(ql, dbName));
        InfluxDBResultMapper resultMapper = new InfluxDBResultMapper();
        return resultMapper.toPOJO(query, clazz);
    }


}
